<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\Db;

class Facebook extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $model = null;
    protected $iscustom = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->token = 'EAAGIZCzxvZADMBALo0C0icxTWMkZB5vSomx1Lp3bsOwRiOZBNp7ckNyvoK5NERZBLaTH2ZCrIbn2TZCyrWi9PiJHAgQB2wira6uE7jgFurrnziaWDCO1IQSwyAYdWLv1ydwDs4dUw1SW0gLeLSjTxq5I5bDYI8utDdWU0Ds3SgcpCFDzI8b3sp4';
    }

    public function accounturl_insights()
    {
        $type = $this->request->request('type');
        $where = array();
        $accounturl = $this->request->request('accounturl');
        if (!empty($accounturl)) {
            $where['id'] = $accounturl;
        }else{
//            $where['id']  = array('egt',56);
        }
        $result = array();
        if(!empty($type)){
            $iscustom = Db::name('fedition_advertising')
                ->where('status','normal')
                ->where($where)
                ->order('updatetime asc')
                ->find();
            if($iscustom){
                $result = $this->insights($iscustom,$type);
                $updatetime['updatetime'] = time();
                Db::name('fedition_advertising')
                    ->where('id',$iscustom['id'])
                    ->update($updatetime);
            }
        }
        $this->success('操作成功',$result);
    }

    public function insights($advertising,$type){
        if ($type == 1) {
            //实时计算当天的数据
            $url = 'https://graph.facebook.com/v13.0/act_'.$advertising['ad_id'].'/insights?access_token='.$this->token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&breakdowns=hourly_stats_aggregated_by_advertiser_time_zone&date_preset=today';
        }elseif($type == 2){
            $url = 'https://graph.facebook.com/v13.0/act_'.$advertising['ad_id'].'/insights?access_token='.$this->token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&breakdowns=hourly_stats_aggregated_by_advertiser_time_zone&date_preset=yesterday';
        } else {
            //实时计算当天的数据
            $url = 'https://graph.facebook.com/v13.0/act_'.$advertising['ad_id'].'/insights?access_token='.$this->token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&breakdowns=hourly_stats_aggregated_by_advertiser_time_zone&date_preset=today';
        }

        $result = $this->geturl($url);
        if (!empty($result)) {
            $result = json_decode($result,true);
            if (!empty($result['data']) && isset($result['data'])) {
                foreach ($result['data'] as $item) {
                    $arr2 = array();
                    $arr2['account'] = $item['account_id'];
                    $fedition_advertising = Db::name('fedition_advertising')->where('ad_id',$arr2['account'])->find();
                    if (!empty($fedition_advertising)) {
                        $arr2['account_id'] = $fedition_advertising['id'];
                        $arr2['accounturl'] = $fedition_advertising['accounturl'];
                    } else {
                        $arr2['account_id'] = 0;
                        $arr2['accounturl'] = 0;
                    }
                    $arr2['date_start'] = strtotime($item['date_start']);
                    $arr2['date_stop'] = strtotime($item['date_stop']);
                    $arr2['impressions'] = $item['impressions'];
                    $arr2['spend'] = $item['spend'];
                    $arr2['hourly'] = $item['hourly_stats_aggregated_by_advertiser_time_zone'];
                    switch ($arr2['hourly']) {
                        case '00:00:00 - 00:59:59':
                            $arr2['hourly_type'] = '1';
                            break;
                        case '01:00:00 - 01:59:59':
                            $arr2['hourly_type'] = '2';
                            break;
                        case '02:00:00 - 02:59:59':
                            $arr2['hourly_type'] = '3';
                            break;
                        case '03:00:00 - 03:59:59':
                            $arr2['hourly_type'] = '4';
                            break;
                        case '04:00:00 - 04:59:59':
                            $arr2['hourly_type'] = '5';
                            break;
                        case '05:00:00 - 05:59:59':
                            $arr2['hourly_type'] = '6';
                            break;
                        case '06:00:00 - 06:59:59':
                            $arr2['hourly_type'] = '7';
                            break;
                        case '07:00:00 - 07:59:59':
                            $arr2['hourly_type'] = '8';
                            break;
                        case '08:00:00 - 08:59:59':
                            $arr2['hourly_type'] = '9';
                            break;
                        case '09:00:00 - 09:59:59':
                            $arr2['hourly_type'] = '10';
                            break;
                        case '10:00:00 - 10:59:59':
                            $arr2['hourly_type'] = '11';
                            break;
                        case '11:00:00 - 11:59:59':
                            $arr2['hourly_type'] = '12';
                            break;
                        case '12:00:00 - 12:59:59':
                            $arr2['hourly_type'] = '13';
                            break;
                        case '13:00:00 - 13:59:59':
                            $arr2['hourly_type'] = '14';
                            break;
                        case '14:00:00 - 14:59:59':
                            $arr2['hourly_type'] = '15';
                            break;
                        case '15:00:00 - 15:59:59':
                            $arr2['hourly_type'] = '16';
                            break;
                        case '16:00:00 - 16:59:59':
                            $arr2['hourly_type'] = '17';
                            break;
                        case '17:00:00 - 17:59:59':
                            $arr2['hourly_type'] = '18';
                            break;
                        case '18:00:00 - 18:59:59':
                            $arr2['hourly_type'] = '19';
                            break;
                        case '19:00:00 - 19:59:59':
                            $arr2['hourly_type'] = '20';
                            break;
                        case '20:00:00 - 20:59:59':
                            $arr2['hourly_type'] = '21';
                            break;
                        case '21:00:00 - 21:59:59':
                            $arr2['hourly_type'] = '22';
                            break;
                        case '22:00:00 - 22:59:59':
                            $arr2['hourly_type'] = '23';
                            break;
                        case '23:00:00 - 23:59:59':
                            $arr2['hourly_type'] = '24';
                            break;
                        default:
                            $arr2['hourly_type'] = '0';
                    }
                    $advertising_n = Db::name('fedition_advertising_info')
                        ->where('account', $arr2['account'])
                        ->where('date_start', $arr2['date_start'])
                        ->where('hourly', $arr2['hourly'])
                        ->find();
                    if (!empty($advertising_n)) {
                        $return = Db::name('fedition_advertising_info')
                            ->where('id', $advertising_n['id'])
                            ->update($arr2);
                    } else {
                        $return = Db::name('fedition_advertising_info')
                            ->insert($arr2);
                    }
                }
                return true;
            }else{
                if (!empty($result['error']) && isset($result['error'])) {
                    return false;
                } else {
                    //如果接口为空
                    return true;
                }
            }
        } else {
            return false;
        }
    }

    function geturl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function posturl($url,$data = array(),$AccessToken=null){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $headerArray =array("charset='utf-8'");
        if(!empty($AccessToken)){
            $headerArray[] = 'Access-Token:'.$AccessToken;
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function updatetime($id = null)
    {
        Cache::rm('rulelist');
        if (!empty($id)) {
            $advertising_roi = Db::name('fedition_advertising_roi')
                ->where('id',$id)
                ->find();
            if (!empty($advertising_roi)) {
                $date_start = $advertising_roi['date_start'];
                $date_start = strtotime(date("Y-m-d",$date_start));
            } else {
                $this->error('未找到相关信息');
            }
        }else {
            $date_start = $this->request->request('date_start');
            if (empty($date_start)) {
                $type = $this->request->request('type');
                if ($type == 1) {
                    $date_start = strtotime(date("Y-m-d",strtotime("today")));
                }elseif($type == 2){
                    $date_start = strtotime(date("Y-m-d",strtotime("yesterday")));
                }else{
                    $date_start = strtotime(date("Y-m-d",strtotime("today")));
                }

            }
        }
//        通过当天零点时间戳进行筛选
        $date_stop = $date_start + 86400;
        $timedate = 'created_at';
        $times = $timedate.'>='.$date_start.' and '.$timedate.'<='.$date_stop;
        $sql = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,count(countnum) as countnums,accounturl
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE accounturl>=56
AND ".$times."
AND (financial_status = 'paid' or financial_status = 'partially_refunded')
GROUP BY accounturl
ORDER BY accounturl ASC";
        $statistics = \think\Db::query($sql);
        if (!empty($statistics)) {
            $arr1 = array();
            $arr2 = array();
            $arr3 = array();
            foreach ($statistics as $k=>$v) {
                $advertising_info = Db::name('fedition_advertising_info')
                    ->where('accounturl',$v['accounturl'])
                    ->where('date_start',$date_start)
                    ->select();
                if (!empty($advertising_info)) {
                    $statistics[$k]['advertising_info'] = $advertising_info;
                    $impressionss = 0;
                    $spends = 0;
                    $newadvertising[1] = array();
                    $newadvertising[2] = array();
                    $newadvertising[3] = array();
                    $newadvertising[4] = array();
                    $newadvertising[5] = array();
                    $newadvertising[6] = array();
                    $newadvertising[7] = array();
                    $newadvertising[8] = array();
                    $newadvertising[9] = array();
                    $newadvertising[10] = array();
                    $newadvertising[11] = array();
                    $newadvertising[12] = array();
                    $newadvertising[13] = array();
                    $newadvertising[14] = array();
                    $newadvertising[15] = array();
                    $newadvertising[16] = array();
                    $newadvertising[17] = array();
                    $newadvertising[18] = array();
                    $newadvertising[19] = array();
                    $newadvertising[20] = array();
                    $newadvertising[21] = array();
                    $newadvertising[22] = array();
                    $newadvertising[23] = array();
                    foreach ($advertising_info as $key=>$val) {
                        $impressionss = $impressionss + $val['impressions'];
                        $spends = $spends + $val['spend'];
                        //时间段精准数据
                        if (!empty($newadvertising[$val['hourly_type']]['impressions'])) {
                            $newadvertising[$val['hourly_type']]['impressions'] = $newadvertising[$val['hourly_type']]['impressions'] + $val['impressions'];
                        } else {
                            $newadvertising[$val['hourly_type']]['impressions'] = $val['impressions'];
                        }
                        if (!empty($newadvertising[$val['hourly_type']]['spend'])) {
                            $newadvertising[$val['hourly_type']]['spend'] = $newadvertising[$val['hourly_type']]['spend'] + $val['spend'];
                        } else {
                            $newadvertising[$val['hourly_type']]['spend'] = $val['spend'];
                        }
                        $newadvertising[$val['hourly_type']]['hourly'] = $val['hourly'];
                        $newadvertising[$val['hourly_type']]['hourly_type'] = $val['hourly_type'];
                        $newadvertising[$val['hourly_type']]['date_start'] = $val['date_start'];
                        //第三层需要
                        if (!empty($newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['impressions'])) {
                            $newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['impressions'] = $newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['impressions'] + $val['impressions'];
                        } else {
                            $newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['impressions'] = $val['impressions'];
                        }
                        if (!empty($newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['spend'])) {
                            $newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['spend'] = $newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['spend'] + $val['spend'];
                        } else {
                            $newadvertising[$val['hourly_type']]['account_class'][$val['account_id']]['spend'] = $val['spend'];
                        }


                    }
                    //创建第一层
                    $arr1['date_start'] = $date_start;
                    $arr1['date_stop'] = $date_stop;
                    $arr1['impressions'] = $impressionss;
                    $arr1['spend'] = $spends;
                    $arr1['hourly'] = date("Y-m-d",$date_start);
                    $arr1['accounturl'] = $v['accounturl'];
                    $arr1['sales'] = $v['total_price'];
                    $arr1['ordershopifycount'] = $v['countnums'];
                    // ROI = 销售额 / 广告
                    $arr1['roi'] = '1:'.number_format((float)$arr1['sales'] / $arr1['spend'], 3);
                    $arr1['pid'] = 0;
                    $arr1['name'] = '总共';
                    $advertising_roi = Db::name('fedition_advertising_roi')
                        ->where('date_start',$arr1['date_start'])
                        ->where('accounturl',$arr1['accounturl'])
                        ->where('pid',0)
                        ->find();
                    if (!empty($advertising_roi)) {
                        Db::name('fedition_advertising_roi')
                            ->where('id',$advertising_roi['id'])
                            ->update($arr1);
                        $pid = $advertising_roi['id'];
                    } else {
                        $arr1['createtime'] = $date_start;
                        $arr1['updatetime'] = time();
                        $pid = Db::name('fedition_advertising_roi')
                            ->insertGetId($arr1);
                    }
                    //计算第二层
                    unset($newadvertising[0]);
                    $arr2 = array();
                    if (!empty($newadvertising)) {
                        foreach ($newadvertising as $a=>$b) {
                            if (!empty($b['hourly_type'])) {
                                switch ($b['hourly_type']) {
                                    case '1':
                                        $arr2['date_start'] = $date_start;
                                        $arr2['date_stop'] = $date_start + 3600;
                                        break;
                                    case '2':
                                        $arr2['date_start'] = $date_start + 3600;
                                        $arr2['date_stop'] = $date_start + 3600*2;
                                        break;
                                    case '3':
                                        $arr2['date_start'] = $date_start + 3600*2;
                                        $arr2['date_stop'] = $date_start + 3600*3;
                                        break;
                                    case '4':
                                        $arr2['date_start'] = $date_start + 3600*3;
                                        $arr2['date_stop'] = $date_start + 3600*4;
                                        break;
                                    case '5':
                                        $arr2['date_start'] = $date_start + 3600*4;
                                        $arr2['date_stop'] = $date_start + 3600*5;
                                        break;
                                    case '6':
                                        $arr2['date_start'] = $date_start + 3600*5;
                                        $arr2['date_stop'] = $date_start + 3600*6;
                                        break;
                                    case '7':
                                        $arr2['date_start'] = $date_start + 3600*6;
                                        $arr2['date_stop'] = $date_start + 3600*7;
                                        break;
                                    case '8':
                                        $arr2['date_start'] = $date_start + 3600*7;
                                        $arr2['date_stop'] = $date_start + 3600*8;
                                        break;
                                    case '9':
                                        $arr2['date_start'] = $date_start + 3600*8;
                                        $arr2['date_stop'] = $date_start + 3600*9;
                                        break;
                                    case '10':
                                        $arr2['date_start'] = $date_start + 3600*9;
                                        $arr2['date_stop'] = $date_start + 3600*10;
                                        break;
                                    case '11':
                                        $arr2['date_start'] = $date_start + 3600*10;
                                        $arr2['date_stop'] = $date_start + 3600*11;
                                        break;
                                    case '12':
                                        $arr2['date_start'] = $date_start + 3600*11;
                                        $arr2['date_stop'] = $date_start + 3600*12;
                                        break;
                                    case '13':
                                        $arr2['date_start'] = $date_start + 3600*12;
                                        $arr2['date_stop'] = $date_start + 3600*13;
                                        break;
                                    case '14':
                                        $arr2['date_start'] = $date_start + 3600*13;
                                        $arr2['date_stop'] = $date_start + 3600*14;
                                        break;
                                    case '15':
                                        $arr2['date_start'] = $date_start + 3600*14;
                                        $arr2['date_stop'] = $date_start + 3600*15;
                                        break;
                                    case '16':
                                        $arr2['date_start'] = $date_start + 3600*15;
                                        $arr2['date_stop'] = $date_start + 3600*16;
                                        break;
                                    case '17':
                                        $arr2['date_start'] = $date_start + 3600*16;
                                        $arr2['date_stop'] = $date_start + 3600*17;
                                        break;
                                    case '18':
                                        $arr2['date_start'] = $date_start + 3600*17;
                                        $arr2['date_stop'] = $date_start + 3600*18;
                                        break;
                                    case '19':
                                        $arr2['date_start'] = $date_start + 3600*18;
                                        $arr2['date_stop'] = $date_start + 3600*19;
                                        break;
                                    case '20':
                                        $arr2['date_start'] = $date_start + 3600*19;
                                        $arr2['date_stop'] = $date_start + 3600*20;
                                        break;
                                    case '21':
                                        $arr2['date_start'] = $date_start + 3600*20;
                                        $arr2['date_stop'] = $date_start + 3600*21;
                                        break;
                                    case '22':
                                        $arr2['date_start'] = $date_start + 3600*21;
                                        $arr2['date_stop'] = $date_start + 3600*22;
                                        break;
                                    case '23':
                                        $arr2['date_start'] = $date_start + 3600*22;
                                        $arr2['date_stop'] = $date_start + 3600*23;
                                        break;
                                    case '24':
                                        $arr2['date_start'] = $date_start + 3600*23;
                                        $arr2['date_stop'] = $date_start + 3600*24;
                                        break;
                                    default:
                                        $arr2['date_start'] = $date_start;
                                        $arr2['date_stop'] = $date_start + 86400;
                                }
                            }else{
                                $arr2['date_start'] = $date_start;
                                $arr2['date_stop'] = $date_start + 86400;
                            }
                            if (!empty($b)) {
                                $arr2['impressions'] = $b['impressions'];
                                $arr2['spend'] = $b['spend'];
                                $arr2['hourly'] = $b['hourly'];
                                $arr2['hourly_type'] = $b['hourly_type'];
                                $arr2['accounturl'] = $v['accounturl'];
                                $times2 = $timedate.'>='.$arr2['date_start'].' and '.$timedate.'<='.$arr2['date_stop'];
                                $sql2 = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,count(countnum) as countnums,accounturl
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE ".$times2."
AND (financial_status = 'paid' or financial_status = 'partially_refunded')
AND accounturl = ".$v['accounturl']."
ORDER BY accounturl ASC";
                                $statistic2 = \think\Db::query($sql2);
                                if (!empty($statistic2[0]['total_price'])) {
                                    $arr2['sales'] = $statistic2[0]['total_price'];
                                    $arr2['ordershopifycount'] = $statistic2[0]['countnums'];
                                    // ROI = 销售额 / 广告
                                    $arr2['roi'] = '1:'.number_format((float)$arr2['sales'] / $arr2['spend'], 3);
                                } else {
                                    $arr2['sales'] = 0;
                                    $arr2['ordershopifycount'] = 0;
                                    // ROI = 销售额 / 广告
                                    $arr2['roi'] = '1:0';
                                }
                                $arr2['pid'] = $pid;
                                $arr2['name'] = '按时间段';
                                Db::name('fedition_advertising_roi')
                                    ->where('date_start',$arr2['date_start'])
                                    ->where('date_stop',$arr2['date_stop'])
                                    ->where('hourly_type',$arr2['hourly_type'])
                                    ->where('accounturl',$arr2['accounturl'])
                                    ->delete();
                                $arr2['createtime'] = $date_start;
                                $arr2['updatetime'] = time();
                                $pid2 = Db::name('fedition_advertising_roi')
                                    ->insertGetId($arr2);
                            }
                            //第三层
                            if (!empty($b['account_class'])) {
                                foreach ($b['account_class'] as $c=>$d) {
                                    $arr3['pid'] = $pid2;
                                    $arr3['name'] = '按广告账户';
                                    $arr3['impressions'] = $d['impressions'];
                                    $arr3['spend'] = $d['spend'];
                                    $arr3['hourly'] = $b['hourly'];
                                    $arr3['hourly_type'] = $b['hourly_type'];
                                    $arr3['accounturl'] = $v['accounturl'];
                                    $arr3['advertising_id'] = $c;

                                    Db::name('fedition_advertising_roi')
                                        ->where('accounturl',$arr3['accounturl'])
                                        ->where('hourly_type',$arr3['hourly_type'])
                                        ->where('advertising_id',$arr3['advertising_id'])
                                        ->delete();
                                    $arr3['createtime'] = $date_start;
                                    $arr3['updatetime'] = time();
                                    Db::name('fedition_advertising_roi')
                                        ->insertGetId($arr3);
                                }
                            }
                        }
                    }
                }
            }
        }
        $this->success('更新成功');
    }

}
